/*
 * Copyright 2011 Quytelda Gaiwin
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.tamalin.panthersleek.engine;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created: Jul 16, 2011
 * @author Quytelda Gaiwin
 */
public class DigestEngine
{
    protected DigestEngine(MessageDigest md)
    {
        messageDigest = md;
    }

    public static DigestEngine getInstance(String algorithm) throws NoSuchAlgorithmException
    {

        MessageDigest md = MessageDigest.getInstance(algorithm);
        return new DigestEngine(md);
    }

    public byte[] digest(byte[] data)
    {
        for(byte b : data)
            messageDigest.update(b);

        return messageDigest.digest();
    }

    public String digestToString(byte[] data, boolean format)
    {
        //Create an array to hold the digest in.
        byte[] digest = null;

        digest = this.digest(data);

        /* Convert the digested bytes to human friendly format. */
        StringBuilder hexBuilder = new StringBuilder();
        for(byte b : digest)
        {
            String hex = Integer.toHexString(b & 0xFF);
            String formatted = (hex.length() == 2) ? hex : "0" + hex;
            hexBuilder.append((format) ? (formatted.toUpperCase() + ":") : formatted);
        }

        String hexCode = hexBuilder.toString();
        return (format) ? hexCode.substring(0, hexCode.length() - 1) : hexCode;
    }

    public String getAlgorithm()
    {
        return messageDigest.getAlgorithm();
    }

    public void setAlgorithm(String algorithm) throws NoSuchAlgorithmException
    {
        messageDigest = MessageDigest.getInstance(algorithm);
    }

    private MessageDigest messageDigest;
}
